package com.iflytek.iot.okhttp.config;

import com.iflytek.iot.common.net.NetWorkTimeout;
import com.iflytek.iot.common.net.SSLSocketFactoryBuilder;
import com.iflytek.iot.common.net.TrustAnyTrustManager;
import com.iflytek.iot.okhttp.template.CustomerRestTemplate;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;

import java.net.Proxy;
import java.util.concurrent.TimeUnit;

/**
 * 抽象template config
 *
 * @author yu 2019/3/25.
 */
public class AbsRestTemplateConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(AbsRestTemplateConfig.class);

    /**
     * 创建restTemplate
     *
     * @param timeout
     * @return
     */
    public CustomerRestTemplate createRestTemplate(NetWorkTimeout timeout, ConnectionPool connectionPool) {
        return buildRestTemplate(timeout, null, connectionPool);
    }

    /**
     * 设置代理
     *
     * @param timeout 超时时间设置
     * @param proxy   代理对象
     * @return
     */
    public CustomerRestTemplate createRestProxyTemplate(NetWorkTimeout timeout, Proxy proxy, ConnectionPool connectionPool) {
        return buildRestTemplate(timeout, proxy, connectionPool);
    }

    private CustomerRestTemplate buildRestTemplate(NetWorkTimeout timeout, Proxy proxy, ConnectionPool connectionPool) {
        LOGGER.debug("connectTimeout={}ms readTimeout={}ms writeTime={}ms", timeout.getConnectTimeout(),
                timeout.getReadTimeout(), timeout.getWriteTimeout());
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(SSLSocketFactoryBuilder.getSslSocketFactory(), new TrustAnyTrustManager())
                .retryOnConnectionFailure(false)
                .connectionPool(connectionPool)
                .hostnameVerifier((s, sslSession) -> true)
                .connectTimeout(timeout.getConnectTimeout(), TimeUnit.MILLISECONDS)
                .readTimeout(timeout.getReadTimeout(), TimeUnit.MILLISECONDS)
                .writeTimeout(timeout.getWriteTimeout(), TimeUnit.MILLISECONDS);
        if (proxy != null) {
            LOGGER.debug("Building proxy for REST connection -> address is {}.", proxy.address().toString());
            builder.proxy(proxy);
        }
        OkHttpClient okHttpClient = builder.build();
        OkHttp3ClientHttpRequestFactory httpClient = new OkHttp3ClientHttpRequestFactory(okHttpClient);
        //Connect timeout
        return new CustomerRestTemplate(httpClient);
    }
}
